home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 72 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  802 b 

  1. Path: news.production.compuserve.com!news
  2. From: Dave Hand <70621.3624@CompuServe.COM>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Integer SQRT(), HELP!
  5. Date: 2 Jan 1996 06:44:54 GMT
  6. Organization: Singular Software, Inc.
  7. Message-ID: <4cak96$f9k$1@mhadg.production.compuserve.com>
  8. References: <4b63tm$al9@alpha.ocbbs.gen.nz>
  9.  
  10. Here is an algorithm that works. I'm not sure if it is optimal or
  11. even faster than just converting your int to a double and using the
  12. standard sqrt() that is on the coprocessor. I only used when I was
  13. doing work on a 286 without a coprocessor.
  14.  
  15. //
  16. // Find the square root of an integer.
  17. //
  18. unsigned long square_root(unsigned long s)
  19.     {
  20.     unsigned long a,prev;
  21.  
  22.     prev = a = (s/5 + 2);
  23.     while(1)
  24.         {
  25.         a = (s/a + a) >> 1;
  26.         if(abs(a - prev) <= 1) break;
  27.         prev = a;
  28.         }
  29.     return(a);
  30.     }
  31.  
  32.